<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            width: 20px;
            height: 20px;   
            background-color: #f00;
            border-radius: 50%;
            position: absolute;
        }
    </style>
</head>
<body>

    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>

    <script>

        const oDivs = document.querySelectorAll('div');

        let t ;


        document.onkeydown = function(e) {
            clearInterval(t)
            console.log(e.key);
            // 下40  右39   上38  左37
            console.log(e.keyCode); 

            let x = oDivs[0].offsetLeft ;
            let y = oDivs[0].offsetTop ;
            let speed = 20 ;

            t = setInterval(() => {
                if(e.keyCode === 40) {
                    y += speed ;
                }
                else if(e.keyCode === 38) {
                    y -= speed
                }
                else if(e.keyCode === 39) {
                    x += speed
                }
                else if(e.keyCode === 37) {
                    x -= speed 
                }


                for(let i = oDivs.length - 1 ; i > 0 ; i--) {
                    oDivs[i].style.top = oDivs[i-1].style.top ;
                    oDivs[i].style.left = oDivs[i-1].style.left ;
                }
                oDivs[0].style.top = y + 'px'
                oDivs[0].style.left = x + 'px'
            } , 300)

         
                   

           
        }

    </script>
    
</body>
</html>